﻿using SchemaMonitor;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Framework;
using SchemaMonitor.json;

public partial class usercontrols_UCPhotos : System.Web.UI.UserControl, CGenerate.IDisplay
{
	public int _cols = 5;
	public int _width = 120;

	public int Width { get { return _width; } set { _width = value; } }
	public int Columns { get { return _cols; } set { _cols = value; } }
	public Table Table { get { return tbl; } }





	public void Display(CPhotoHashList list) { Display(list, new List<Guid>(0), new CPagingInfo(1000)); }
	public void Display(IList list, CPagingInfo pi, EShow show = EShow.All, bool? isLhs = null)
	{
		Display(list, new List<Guid>(0), pi, show, isLhs);
	}
	public void Display(IList list, List<Guid> selected, CPagingInfo pi, EShow show = EShow.All, bool? isLhs = null)
	{
		var u = CSession.User;

		var tr = new TableRow();
		var taken = new List<int>(Columns);
		foreach (CPhotoHash ph in list)
		{
			var index = (list.IndexOf(ph) + pi.Offset);

			//New Row?
			if (tr.Cells.Count == Columns)
			{
				tbl.Rows.Add(tr);
				tr = new TableRow();
			}

			var comments = string.Empty;
			foreach (var i in ph.ChapterPictures)
			{
				var c = i.Chapter;
				var n = c.Node_(u);
				var p = new CSoftPost(n.Root, u);
				foreach (var j in ph.Photos)
				{
					var pp = p.GetPhoto(j.ID);
					if (null != pp)
						if (null != pp.Comments && pp.Comments.Count > 0)
							foreach (var k in pp.Comments)
							{
								comments += string.Concat("[", k.Name, "] ", k.Message, "\r\n");
								if (null != k.Comments)
									foreach (var kk in k.Comments)
										comments += string.Concat("\t[", k.Name, "] ", k.Message, "\r\n");

							}
				}
			}


			if (!string.IsNullOrEmpty(ph.PhotoCaptions))
				if (!string.IsNullOrEmpty(comments))
					comments = string.Concat(ph.PhotoCaptions + "\r\n\r\nComments:\r\n", comments);
				else
					comments = ph.PhotoCaptions;

			//New Cell
			var td = new TableCell();
			tr.Cells.Add(td);
			td.VerticalAlign = VerticalAlign.Top;
			td.Controls.Add(Display(ph.PhotoMd5, selected, show, isLhs, comments));

			if (show == EShow.ForPost && isLhs.HasValue && isLhs.Value)
			{
				var txt = new TextBox();
				txt.Text = index.ToString();
				txt.Style.Add("width", "20px");
				txt.ID = "txt_" + index;
				txt.AutoPostBack = true;
				txt.TextChanged += Txt_TextChanged;
				td.Controls.Add(txt);
			}

			AddLabel(td, comments);


		}

		//Remainder
		if (tr.Cells.Count > 0)
		{
			PadTo(tr, Columns);
			tbl.Rows.Add(tr);
		}
	}

	private void Txt_TextChanged(object sender, EventArgs e)
	{
		TextBox txt = (TextBox)sender;
		var newIndex = CTextbox.GetInteger(txt);
		if (newIndex == int.MinValue) return;
		if (newIndex < 0) newIndex = 0;

		var s = txt.ID;
		var i = s.IndexOf("txt_");
		s = s.Substring(i + 4);
		var index = int.Parse(s);

		var chapterId = CWeb.RequestInt("chapterId");
		var c = CChapter.Cache.GetById(chapterId);

		var list = new CChapterPictureList(c.ChapterPictures);
		if (newIndex > list.Count - 1) newIndex = list.Count - 1;
		var item = list[index];
		list.Remove(item);
		list.Insert(newIndex, item);
		list.ResetOrdinals();
		list.SaveAll();
		CChapterPicture.Cache = null;
		Response.Redirect(Request.RawUrl);
	}

	public void Display(List<CSoftPhoto> list)
	{
		var u = CSession.User;

		var tr = new TableRow();
		var taken = new List<int>(Columns);
		foreach (CSoftPhoto ph in list)
		{
			var index = (list.IndexOf(ph));

			//New Row?
			if (tr.Cells.Count == Columns)
			{
				tbl.Rows.Add(tr);
				tr = new TableRow();
			}

			var caption = ph.Description;
			if (caption.Length == 0)
				caption = ph.Title;

			var comments = string.Empty;
			if (null != ph.Comments && ph.Comments.Count > 0)
				foreach (var k in ph.Comments)
				{
					comments += string.Concat("[", k.Name, "] ", k.Message, "\r\n");
					if (null != k.Comments)
						foreach (var kk in k.Comments)
							comments += string.Concat("\t[", k.Name, "] ", k.Message, "\r\n");
				}



			if (!string.IsNullOrEmpty(caption))
				if (!string.IsNullOrEmpty(comments))
					comments = string.Concat(caption + "\r\n\r\nComments:\r\n", comments);
				else
					comments = caption;

			//New Cell
			var td = new TableCell();
			tr.Cells.Add(td);
			td.VerticalAlign = VerticalAlign.Top;
			td.Controls.Add(Display(ph, comments));

			if (ph.IsShare && !string.IsNullOrEmpty(ph.Url))
			{
				var lnk = new HyperLink();
				lnk.Text =string.Concat(ph.Type.ToUpper(), ": ", ph.Title);
				lnk.ToolTip = HttpUtility.UrlDecode(ph.Url);
				lnk.NavigateUrl = ph.Url;
				lnk.Target = "_blank";
				td.Controls.Add(lnk);

				var s = ph.Url;
				if (s.Contains(".php?u="))
				{
					s = s.Substring(s.IndexOf(".php?u=") + 7);
					if (s.Contains("&"))
						s = s.Substring(0, s.IndexOf("&"));
					lnk.NavigateUrl = HttpUtility.UrlDecode(s);
					lnk.ToolTip = lnk.NavigateUrl;
				}
			
			}
			else
				AddLabel(td, comments);


		}

		//Remainder
		if (tr.Cells.Count > 0)
		{
			PadTo(tr, Columns);
			tbl.Rows.Add(tr);
		}
	}




	private Control Display(Guid md5, List<Guid> selected, EShow show, bool? isLhs, string caption)
	{
		var img = Image(md5, this.Width, caption);

		var div = Panel(img, selected.Contains(md5));
		div.ID = "d" + md5.ToString().Substring(0, 6);


		var lnk = Link(md5, show, isLhs);
		lnk.Controls.Add(div);
		//AddLabel(lnk, caption);
		if (show == EShow.Select || show == EShow.Laptop || show == EShow.Delete || show == EShow.XRated)
			lnk.NavigateUrl = "javascript:AddOrRemove('" + md5.ToString() + "', '" + div.ClientID + "')"; //selected.Contains(md5) ? CSitemap.PhotoRem(show, md5) : CSitemap.PhotoAdd(show, md5);

		return lnk;

	}
	private Control Display(CSoftPhoto p, string caption)
	{
		if (!p.Target.HasValue)
			return new Literal();

		var img = Image(p.Target.HasValue ? p.Target.Value : 0, this.Width, caption);

		var div = Panel(img, false);

		if (Columns > 1)
			return div;
		return img;
	}



	private void AddLabel(Control ctrl, Image img) { AddLabel(ctrl, img.ToolTip); }
	private void AddLabel(Control ctrl, string text)
	{
		if (string.IsNullOrEmpty(text))
			return;

		var lbl = new Label();
		lbl.Font.Size = new FontUnit("10px");
		//lbl.Style.Add("position", "absolute");
		//lbl.Style.Add("top", "50px");
		//lbl.Style.Add("left", "50px");
		lbl.Text = HttpUtility.HtmlEncode(text).Replace("\r\n", "<br/>").Replace("\n", "<br/>");

		var div = Panel();
		div.Controls.Add(lbl);

		ctrl.Controls.Add(div);
	}

	private Panel Panel(int moreHeight = 50)
	{
		var div = new Panel();
		div.Style.Add("max-height", string.Concat(Width + moreHeight, "px"));
		div.Style.Add("width", string.Concat(Width + 20, "px"));
		div.Style.Add("overflow", "auto");
		return div;
	}
	private Panel Panel(Image img, bool isSelected)
	{
		var div = Panel();
		div.CssClass = isSelected ? "sel" : "img";
		div.Controls.Add(img);
		return div;
	}




	private HyperLink Link(Guid md5, EShow show, bool? isLhs)
	{
		var url = CSitemap.PhotoDetails(md5);
		var tip = "Click to EDIT";
		if (isLhs.HasValue)
		{
			if (isLhs.Value)
			{
				url = CSitemap.PhotoRem(show, md5);
				tip = "Click to REMOVE";
			}
			else
			{
				tip = "Click to ADD";
				url = CSitemap.PhotoAdd(show, md5);
			}
		}

		return new HyperLink() { NavigateUrl = url, ToolTip = tip };
	}
	private static Image Image(Guid md5, int width, string caption)
	{
		string s = Framework.CBinary.ToBase64(md5.ToByteArray());
		if (String.IsNullOrEmpty(caption))
			caption = s;

		var img = new Image();
		img.Width = new Unit(width);
		img.ImageUrl = CSitemap.Photo(md5);
		img.AlternateText = string.Concat(s, ".jpg");	
		img.ToolTip = caption;
		return img;
	}
	private static Image Image(long id, int width, string caption)
	{
		var img = new Image();
		img.Width = new Unit(width);
		img.ImageUrl = CSitemap.Photo(id);
		img.AlternateText = string.Concat(id, ".jpg");
		img.ToolTip = caption;
		return img;
	}




	private static void PadTo(TableRow tr, int cols)
	{
		while (tr.Cells.Count < cols)
		{
			var s = new TableCell();
			s.Text = "&nbsp;";
			tr.Cells.Add(s);
		}
	}


	public string ToHtml(int cols, int width, CPhotoHashList list)
	{
		System.Text.StringBuilder sb = new System.Text.StringBuilder();
		System.IO.StringWriter stWriter = new System.IO.StringWriter(sb);
		System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter);
		this.Columns = cols;
		this.Width = width;
		this.Display(list);
		this.RenderControl(htmlWriter);
		return sb.ToString();
	}

}